import pandas as pd
import json

# 1. 读取数据（假设Excel中有"词语"、"极性"、"强度"三列）
df = pd.read_excel('E:/词向量/dataset/情感词汇本体/情感词汇本体.xlsx', usecols=['词语', '极性', '强度'])

# 2. 计算情感得分
def calculate_sentiment(row):
    polarity = 1.0 if row['极性'] == 1 else (-1.0 if row['极性'] == 2 else 0.0)
    return polarity * row['强度']

df['情感得分'] = df.apply(calculate_sentiment, axis=1)

# 3. 生成知识图谱JSON
knowledge_graph = {
    "words": {
        row['词语']: {
            "polarity": 1.0 if row['极性'] == 1 else (-1.0 if row['极性'] == 2 else 0.0),
            "intensity": float(row['强度']),
            "sentiment_score": float(row['情感得分'])
        }
        for _, row in df.iterrows()
    }
}

with open('emotion_kg.json', 'w', encoding='utf-8') as f:
    json.dump(knowledge_graph, f, ensure_ascii=False, indent=2)

# 生成描述文件，带容错判断的版本
with open('entity_desc.txt', 'w', encoding='utf-8') as f:
    for _, row in df.iterrows():
        score = row['情感得分']
        if abs(score) < 1e-6:  # 处理浮点零值
            polarity_type = "中性"
        elif score > 0:
            polarity_type = "正向"
        else:
            polarity_type = "负面"
        
        desc = f"{row['词语']}\t{polarity_type}情感词，强度:{row['强度']:.2f}，得分:{score:.2f}"
        f.write(desc + '\n')



